const db = uniCloud.database();
const selfUtils = require('self-utils')
module.exports = {
  _before: async function() { // 通用预处理器
    this.userInfo = await selfUtils.getUserInfo(this)
  },
  async add(data) {
    if (!this.userInfo.uid) return this.userInfo

    data.user_id = this.userInfo.uid
    data.time = Date.now()

    if (data.selected) {
      await db.collection('ly-mall-address').where({
        user_id: this.userInfo.uid
      }).update({
        selected: false
      })
    }
    return await db.collection('ly-mall-address').add(data)
  },
  async getAddrList() {
    if (!this.userInfo.uid) return this.userInfo

    return await db.collection('ly-mall-address').where({
      user_id: this.userInfo.uid
    }).orderBy("selected", "desc").orderBy("time", "desc").get()
  },
  //设置默认地址，将该用户其他地址先更新为非默认
  async setDefault(id) {
    if (!this.userInfo.uid) return this.userInfo

    await db.collection('ly-mall-address').where({
      user_id: this.userInfo.uid
    }).update({
      selected: false
    })

    db.collection('ly-mall-address').doc(id).update({
      selected: true
    })
  },
  //根据id获取地址信息
  async getOneAddr(id) {
    return await db.collection('ly-mall-address').doc(id).get()
  },
  //维护地址时需考虑下列两种情况
  //非默认地址->默认地址
  //默认地址->非默认地址
  async updateOne(data) {
    if (!this.userInfo.uid) return this.userInfo

    let newData = {
      ...data
    };
    delete newData._id
    if (newData.selected) {
      await db.collection('ly-mall-address').where({
        user_id: this.userInfo.uid
      }).update({
        selected: false
      })
      await db.collection('ly-mall-address').doc(data._id).update(newData)
    } else {
      await db.collection('ly-mall-address').doc(data._id).update(newData)
    }
  },
  //获取默认地址信息
  async getDefAddress() {
    if (!this.userInfo.uid) return this.userInfo
    return await db.collection('ly-mall-address').where({
      user_id: this.userInfo.uid,
      selected: true
    }).get()
  }

}